<template>
  <div class="app-container">
    <el-card class="filter-container" :style="{ marginBottom: '20px' }" :shadow="defaultData.cardShadow">
      <div class="operate-container">
        <div>
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
        </div>
        <div>
          <el-button style="float: right" type="primary" @click="getList()">
            搜索
          </el-button>
          <el-button style="float: right; margin-right: 15px" @click="handleResetSearch()">
            重置
          </el-button>
        </div>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="powerfulTableData.listQuery">
          <div class="screenForm">
            <el-form-item label="订单号：">
              <el-input v-model="powerfulTableData.listQuery.orderNumber" placeholder="请输入订单号" clearable />
            </el-form-item>
            <el-form-item label="城市:" style="width: 300px">
              <area-code v-model:provinceCode="powerfulTableData.listQuery.provinceCode"
                v-model:cityCode="powerfulTableData.listQuery.cityCode" :showArea="false" style="width: 100%" />
            </el-form-item>
            <el-form-item label="车牌号：">
              <el-input v-model="powerfulTableData.listQuery.plateNumber" placeholder="请输入车牌号" clearable />
            </el-form-item>
            <el-form-item label="订单状态：" style="width: 250px">
              <el-select v-model="powerfulTableData.listQuery.orderState" placeholder="请选择订单状态" clearable>
                <el-option v-for="(v) in orderStatusMap.keys()" :key="v" :label="orderStatusMap.get(v)" :value="v" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单来源：" style="width: 250px">
              <el-select v-model="powerfulTableData.listQuery.orderSource" placeholder="请选择订单来源" clearable>
                <el-option v-for="(item) in orderSourceList" :key="item.partnerUuid" :label="item.partnerName"
                  :value="item.partnerUuid" />
              </el-select>
            </el-form-item>
            <el-form-item label="用车合作方：" prop="useCarPartner" v-if="userStore.accountType == 1">
              <el-select v-model="powerfulTableData.listQuery.useCarPartner" filterable clearable style="width: 100%"
                placeholder="请选择用车合作方">
                <el-option v-for="item in partnerList" :key="item.partnerUuid" :label="item.partnerName"
                  :value="item.partnerUuid" />
              </el-select>
            </el-form-item>
            <!--  -->
            <el-form-item label="订单类型：" style="width: 250px">
              <el-select v-model="powerfulTableData.listQuery.orderType" placeholder="请选择订单类型" clearable>
                <el-option v-for="(item, index) in [...orderTypeMap].map(([value, label]) => ({ label, value }))"
                  :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间：">
              <el-date-picker v-model="powerfulTableData.listQuery.date" type="daterange" range-separator="至"
                value-format="YYYY-MM-DD" format="YYYY-MM-DD" start-placeholder="开始时间" end-placeholder="结束时间" />
            </el-form-item>
            <el-form-item label="服务时间：">
              <el-date-picker v-model="powerfulTableData.listQuery.serviceTime" type="daterange"
                value-format="YYYY-MM-DD" format="YYYY-MM-DD" range-separator="至" start-placeholder="开始时间"
                end-placeholder="结束时间" />
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-card>

    <el-card :shadow="defaultData.cardShadow">
      <div class="operate-container">
        <div>
          <i class="el-icon-tickets"></i>
          <span>数据列表</span>
        </div>

        <div>
          <el-button type="success" class="btn-add" @click="handleExport()" v-if="userStore.accountType == 1">
            导出订单
          </el-button>
          <el-button type="primary" class="btn-add" @click="handleAdd()" v-if="![3, 4].includes(userStore.accountType)">
            创建订单
          </el-button>
          <el-button type="primary" plain class="btn-add" @click="handleTempAdd()" v-if="userStore.accountType == 1">
            创建临时用车
          </el-button>
        </div>
      </div>

      <div>
        <PowerfulTable :list="powerfulTableData.list" :header="header" :property="property" @size-change="getList"
          @component-event="handleComponentChange" @btn-click="handleBtnClick">
          <template #orderState="{ row }">
            <el-tag :type="orderColorMap.get(row.orderState) as any">
              {{ orderStatusMap.get(row.orderState) }}
            </el-tag>
          </template>
          <template #orderType="{ row }">
            <el-tag :type="orderTypeColorMap.get(row.orderType) as any">
              {{ orderTypeMap.get(row.orderType) }}
            </el-tag>
          </template>
          <template #serviceStartTime="{ row }">
            <div>{{ formatTime(row.serviceStartTime) }}</div>
          </template>
          <template #serviceEndTime="{ row }">
            <div>{{ formatTime(row.serviceEndTime) }}</div>
          </template>
          <template #confirmAcceptOrderTime="{ row }">
            <div>{{ formatTime(row.confirmAcceptOrderTime) }}</div>
          </template>
          <template #startRouteTime="{ row }">
            <div>{{ formatTime(row.startRouteTime) }}</div>
          </template>
          <template #createTime="{ row }">
            <div>{{ formatTime(row.createTime) }}</div>
          </template>
          <template #updateTime="{ row }">
            <div>{{ formatTime(row.updateTime) }}</div>
          </template>
          <template #serviceStartTimeStr="{ row }">
            <div>{{ formatTime(row.serviceStartTimeStr) }}</div>
          </template>
          <template #address="{ row }">
            <div>{{ row.departureAddress }} - {{ row.destinationAddress }}</div>
          </template>
          <template #operation="{ row }">

            <el-dropdown>
              <el-button size="small">
                更多操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="row.orderState < 30 && [1, 3].includes(userStore.accountType)">
                    <el-button type="primary" size="small" @click="handleBtnClick({ params: 'dispatch', row } as any)">
                      调度
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="row.orderState == 10 && row.orderPoolState == 0 && userStore.accountType != 4">
                    <el-button type="success" plain size="small"
                      @click="handleBtnClick({ params: 'joinOrderPool', row } as any)">
                      加入订单池
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="row.orderState == 10 && row.orderPoolState == 1 && userStore.accountType != 4">
                    <el-button type="danger" plain size="small"
                      @click="handleBtnClick({ params: 'shiftOutOrderPool', row } as any)">
                      移除订单池
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="[20, 30].includes(row.orderState) && userStore.accountType != 4">
                    <el-button type="danger" plain size="small"
                      @click="handleBtnClick({ params: 'finishOrder', row } as any)">
                      结束订单
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="row.orderState < 30 && [1, 3].includes(userStore.accountType)">
                    <el-button type="primary" plain size="small"
                      @click="handleBtnClick({ params: 'tempDispatch', row } as any)">
                      临时调度
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="row.orderState < 30 && [1].includes(userStore.accountType)">
                    <el-button type="warning" size="small"
                      @click="handleBtnClick({ params: 'assignOrder', row } as any)">
                      分配
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="row.orderState < 30 && ![3, 4].includes(userStore.accountType)">
                    <el-button type="success" size="small" @click="handleBtnClick({ params: 'edit', row } as any)">
                      编辑
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="row.orderState <= 30 && ![3, 4].includes(userStore.accountType)">
                    <el-button type="danger" size="small" @click="handleBtnClick({ params: 'remove', row } as any)">
                      作废
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type="info" size="small" @click="handleBtnClick({ params: 'detail', row } as any)">
                      详情
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

          </template>
          <!-- <template #Number="{ row }">
            <div>{{ row.orderType == 4 ? '车次号' : '航班号' }}</div>
          </template> -->
          <!--  -->
        </PowerfulTable>
        <el-pagination v-model:current-page="powerfulTableData.listQuery.pageNum" class="pagination-container"
          v-model:page-size="powerfulTableData.listQuery.pageSize" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next" :total="powerfulTableData.total" @size-change="sizeChange"
          @current-change="getList" />
      </div>
    </el-card>

    <!-- 编辑区 -->
    <Dispatch v-model:dialog="dispatchDialog" v-model:currentForm="dispatchModel" @refresh="getList" />
    <TempDispatch v-model:dialog="tempDispatchDialog" v-model:currentForm="tempDispatchModel" @refresh="getList" />
    <AssignOrder v-model:dialog="assignOrderDialog" v-model:currentForm="assignOrderModel" @refresh="getList" />
    <FinishOrder v-model:dialog="finishOrderDialog" v-model:currentForm="finishOrderModel" @refresh="getList" />
    <Update v-model:dialog="isDialog" v-if="isDialog" v-model:currentForm="currentForm" @refresh="getList" />
    <TempUpdate v-model:dialog="tempDialog" v-if="tempDialog" v-model:currentForm="currentForm" @refresh="getList" />
    <!-- 详情弹窗 -->
    <Detail v-model:dialog="detailDialog" v-model:currentForm="detailModel" />
  </div>
</template>
<script lang="ts" setup>
import { orderQuery, invalidOrder, exportOrder, joinOrderPool, shiftOutOrderPool, queryOrderTimeDistribution } from '@/api/order'
import { useData, Model } from './indexData'
import { Handlers } from 'el-plus-powerful-table'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores'
import Update from './update.vue'
import AreaCode from "@/components/area-code/index.vue"
import FinishOrder from './finishOrder.vue'
import TempUpdate from './tempUpdate.vue'
import Dispatch from './dispatch.vue'
import TempDispatch from './tempDispatch.vue'
import { partnerQuery, } from '@/api/user'

import Detail from './detail.vue'
import AssignOrder from './assignOrder.vue'
import { formatTime, downloadFile } from '@/utils'
import { property, orderStatusMap, orderTypeMap, orderColorMap, orderTypeColorMap } from '@/config/constants'
const { header, powerfulTableData, currentForm, isDialog, dispatchDialog, orderSourceList } = useData()
import { defaultData as defaultForm } from './indexData'
const userStore = useUserStore()

const dispatchModel = reactive({
  orderUuid: '',
  driverUuid: '',
  carUuid: '',
})

const partnerList = ref<any>([])
const tempDialog = ref(false)
const assignOrderModel = reactive({
  orderUuid: '',
  useCarGroup: '',
})

const tempDispatchModel = reactive({
  orderUuid: '',
  plateNumber: '',
  modelName: '',
  color: '',
  driverName: '',
  driverMobileNumber: '',
})

const detailDialog = ref(false)
const tempDispatchDialog = ref(false)
const finishOrderDialog = ref(false)
const assignOrderDialog = ref(false)
const detailModel = reactive({
  orderUuid: ''
})
const finishOrderModel = reactive({
  orderUuid: '',
  serviceEndTime: '',
  pickUpPointFileList: [],
  endRouteFileList: [],
  remark: '',
})

// 获取用户列表
const getList = () => {
  orderQuery({
    ...powerfulTableData.listQuery,
    startCreateTime: powerfulTableData.listQuery.date[0],
    endCreateTime: powerfulTableData.listQuery.date[1],
    startServiceTimeStr: powerfulTableData.listQuery.serviceTime[0],
    endServiceTimeStr: powerfulTableData.listQuery.serviceTime[1],
  }).then((res) => {
    console.log(res)
    powerfulTableData.list = res.data.list
    powerfulTableData.total = res.data.total
  })
}
// 分页大小改变
const sizeChange = (val: number) => {
  powerfulTableData.listQuery.pageSize = val
  getList()
}

onMounted(() => {
  getList()
  partnerQuery({ pageNum: 1, pageSize: 1000 }).then((res: any) => {
    partnerList.value = res.data.list || []
  })
})

const handleComponentChange: Handlers['component-event'] = (payload) => {
  switch (payload.componentName) {
    // 停用事件
    case 'switch':
      const e = payload.row
      if (userStore.userInfo.id == e.id && e.status === 0) {
        ElMessage.error('你的账号已被停用！')
      }
      break
  }
}

const handleAdd = () => {
  Object.assign(currentForm.value, defaultForm())
  isDialog.value = true;
}

const handleTempAdd = () => {
  Object.assign(currentForm.value, defaultForm())
  tempDialog.value = true;
}

const handleExport = () => {
  exportOrder({ ...powerfulTableData.listQuery, startCreateTime: powerfulTableData.listQuery.date[0], endCreateTime: powerfulTableData.listQuery.date[1] }).then((res: any) => {
    // 确保 Blob 的 type 正确（后端设置正确通常不需要重新指定）
    // const excelBlob = new Blob([res]);
    // window.open(URL.createObjectURL(excelBlob));
    downloadFile(res, '订单导出.xlsx')
  })
}

const handleBtnClick: Handlers['btn-click'] = ({ params, row }) => {
  console.log(row)
  switch (params) {
    case 'edit':
      if (row.orderNature == 2) {
        tempDialog.value = true
      } else {
        isDialog.value = true;
      }
      Object.assign(currentForm.value, { orderUuid: row.orderUuid })
      break
    case 'remove':
      remove(row)
      break
    case 'dispatch':
      dispatchModel.orderUuid = row.orderUuid
      dispatchModel.driverUuid = row.driverUuid
      dispatchModel.carUuid = row.carUuid
      dispatchDialog.value = true
      break
    case 'tempDispatch':
      tempDispatchModel.orderUuid = row.orderUuid
      tempDispatchDialog.value = true
      break
    case 'assignOrder':
      assignOrderModel.orderUuid = row.orderUuid
      assignOrderDialog.value = true
      break
    case 'joinOrderPool':
      ElMessageBox.confirm('是否确认加入订单池', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        joinOrderPool({ orderUuid: row.orderUuid }).then(() => {
          ElMessage.success('加入订单池成功！')
          getList()
        })
      })
      break
    case 'shiftOutOrderPool':
      ElMessageBox.confirm('是否确认移除订单池', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        shiftOutOrderPool({ orderUuid: row.orderUuid }).then(() => {
          ElMessage.success('移除订单池成功！')
          getList()
        })
      })
      break
    case 'finishOrder':
      finishOrderModel.orderUuid = row.orderUuid
      finishOrderDialog.value = true
      break
    case 'detail':
      detailModel.orderUuid = row.orderUuid
      console.log(detailModel)
      detailDialog.value = true
      break
  }
}

const remove = (row: Model) => {
  ElMessageBox.confirm('是否确认作废订单', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    invalidOrder({ orderUuid: row.orderUuid }).then(() => {
      ElMessage.success('删除成功！')
      getList()
    })
  })
}

// 分配菜单
const handleAddRole = () => {
  // switchs.role = false
  // powerfulTableData.list = powerfulTableData.list.map((item: RowType) => {
  //   if (item.id == (currentForm.value as RowType).id) {
  //     item = currentForm.value as RowType
  //   }
  //   return item
  // })
}

// 重置
const handleResetSearch = () => {
  Object.keys(powerfulTableData.listQuery).forEach((item: any) => {
    let arr = ['pageNum', 'pageSize', 'date']
    if (arr.indexOf(item) == -1) {
      // @ts-ignore
      (powerfulTableData.listQuery as { [s: string]: string | number })[item] = ''
      powerfulTableData.listQuery['date'] = []
    }
  })
  getList()
}
</script>
